package com.tbm.console.base.service;

import com.tbm.console.util.PageData;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class CommonServiceImpl<T> implements CommonService<T> {
    @Override
    public List<T> findAll() {
        return findAll(new PageData());
    }

    @Override
    public List<T> findAll(Integer start, Integer length) {
        return findAll(new PageData(),start,length);
    }

    @Override
    public  List<T> findAll(PageData pageData) {
        Integer length = Integer.valueOf(String.valueOf(this.count(pageData)));
        if(0==length){
            return new ArrayList<>();
        }
        return findAll(pageData, 0, length);
    }

    @Override
    public abstract List<T> findAll(PageData pageData, Integer start, Integer length) ;

    @Override
    public long count() {
        return count(new PageData());
    }

    @Override
    public long count(T t) {
        return 0;
    }

    @Override
    public abstract long count(PageData pageData) ;

    @Override
    public boolean deleteById(Integer id) {
        return false;
    }

    @Override
    public boolean deleteByIds(Iterable<T> iterable) {
        return false;
    }

    @Override
    public T save(T t) {
        List<T> list = saveAll(Arrays.asList(t));
        if(list.size()==1){
            return list.get(0);
        }else{
            return null;
        }
    }

    @Override
    public abstract List<T> saveAll(List<T> ts) ;

    @Override
    public T findById(Integer id) {
        Integer[] ids = new Integer[]{id};
        List<T> allById = findAllById(ids);
        return allById.get(0);
    }

    @Override
    public abstract List<T> findAllById(Integer[] ids) ;


    public abstract Specification<T> getSpecification(PageData pageData) ;
}
